<?php

namespace app\admin\controller\dingdan;

use app\admin\model\BillRecord;
use app\common\controller\Backend;
use think\Db;
use think\Queue;
use app\admin\model\Orders as OrdersModel;
/**
 * 订单管理
 *
 * @icon  fa fa-bitcoin
 */
class Orders extends Backend
{
    public $admin_id = null;
    public $user_type = null;
    public function _initialize()
    {
        $this->admin_id = getAdminInfo('id');
        $model = new OrdersModel();
        $statusList = $model->statusList();
        $this->view->assign('statusList',$statusList);
        parent::_initialize();
    }
    /**
     * View
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null);
            $status = input('status',0);
            $where2 = [];
            if(!empty($status)){
                $where2['status'] = $status;
            }

            $model = new OrdersModel();
            if(empty($where2)){
                $list = $model
                    ->with(['user','phone'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }else{
                $list = $model
                    ->with(['user','phone'])
                    ->where($where2)
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }

            $statusColor = $model->getStatusColor();
            $statusList = $model->statusList2();
            $data = $list->items();
            foreach ($data as &$item){
               $item['status_color'] = $statusColor[$item['status']];
               $item['status_str'] = $statusList[$item['status']];
            }
            $result = array("total" => $list->total(), "rows" => $data,"extend"=>[]);

            return json($result);
        }

        return $this->view->fetch();

    }

    /**
     * Add
     */
    public function add(){

        $admin_id = getAdminInfo('id');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $msg = $this->validate($params,'Orders');
            if($msg != 'true')
                $this->error($msg);


            if(!isset($params['title'])){
                $this->error("请添加产品");
            }
            $product_num = count($params['title']);
            for($num = 0;$num<$product_num;$num++){
                if(empty($params['title'][$num])){
                    $this->error("请填写产品名");
                }
                if(empty($params['thumbs'][$num])){
                    $this->error("请传图片信息");
                }
                if(empty($params['thumbs'][$num])){
                    $this->error("请填写价格");
                }
                if(empty($params['nums'][$num])){
                    $this->error("请填写数量");
                }
                if(empty($params['factory_id'][$num])){
                    $this->error("请选择供货商");
                }
            }


//                ppd($params);
            $ordersModel = new OrdersModel();

            //计入记录
            try {
                Db::startTrans();

                $invoice = date("YmdHis",time()).rand(10000,99999);
                $invoice = substr($invoice,2);
                $invoice = trim($invoice);
                $inData = [];
                $inData['user_id'] =$admin_id;
                $inData['order_bianhao'] = $invoice;
                $inData['status'] = $params['status'];
                $inData['name'] = $params['name'];
                $inData['email'] = $params['email'];
                $inData['mobile'] = $params['mobile'];
                $inData['address'] = $params['address'];
                $inData['sex'] = $params['sex'];
                $inData['payaccount_id'] = $params['payaccount_id'];
                $inData['total_price'] = $params['total_price'];
                $inData['yufu_price'] = $params['yufu_price'];
                $weikuan_price = 0;
                if($params['need_weikuan'] == 1){
                    $weikuan_price = round($params['total_price']-$params['yufu_price'],2);
                }
                $inData['weikuan_price'] = $weikuan_price;
                $inData['need_weikuan'] = $params['need_weikuan'];
                $inData['remark'] = $params['remark'];
                $inData['create_time'] = date("Y-m-d H:i:s");
                $inData['update_time'] = date("Y-m-d H:i:s");
                $order_id = $ordersModel->insertGetId($inData);

                $ordersProductModel = new OrdersProduct();
                $recordData = [];
                for($num = 0;$num<$product_num;$num++){

                    $thumbs = $params['thumbs'][$num];
                    $thumbsArr = json_decode($thumbs,true);
                    $thumb = '';
                    $all_thumb = [];
                    foreach ($thumbsArr as $key=> $oneThumb){
                        if($key == 0){
                            $thumb = $oneThumb['url'];
                        }
                        $all_thumb[] = $oneThumb['url'];
                    }

                    $temp = [
                        'order_bianhao'=>$invoice,
                        'good_id'=>0,
                        'user_id'=>$admin_id,
                        'title'=>$params['title'][$num],
                        'thumb'=>$thumb,
                        'thumbs'=>implode(',',$all_thumb),
                        'guige'=>$params['guige'][$num],
                        'xinghao'=>$params['xinghao'][$num],
                        'price'=>$params['price'][$num],
                        'nums'=>$params['nums'][$num],
                        'total_price'=>round($params['price'][$num]*$params['nums'][$num],2),
                        'url'=>$params['url'][$num],
                        'remark'=>$params['remark2'][$num],
                        'attachment'=>'',
                        'factory_id'=>$params['factory_id'][$num],
                        'cost_price'=>$params['cost_price'][$num],
                        'factory_status'=>$ordersProductModel::STATUS_WAITDIAO,
                        'create_time'=>date("Y-m-d H:i:s"),
                    ];
                    $recordData[] = $temp;

                }
                $ordersProductModel->insertAll($recordData);

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                trace_log($e->getLine()."||".$e->getMessage()."||".$e->getFile(),'order_error_add');
                $this->error($e->getMessage().$e->getLine(),'','',6);
            }

            $this->success("添加成功");
        }

        $factoryDataArr = db('factory')->where("status",'=',1)->select();
        $accountDataArr = db('payaccount')->where("status",'=',1)->select();
        $uploadUrl = request()->domain()."/admin.php/ajax/upload";
        $this->view->assign('need_weikuan',-1);
        $this->view->assign('status',1000);
        $this->view->assign('sex',1);
        $this->view->assign('id',0);
        $this->view->assign('orderData',[]);
        $this->view->assign('factoryDataArr',$factoryDataArr);
        $this->view->assign('accountDataArr',$accountDataArr);
        $this->assignconfig('uploadUrl',$uploadUrl);
        return $this->view->fetch();
    }

    /**
     * Edit
     */
    public function edit($ids = null)
    {
        $admin_id = getAdminInfo('id');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $msg = $this->validate($params,'Orders');
            if($msg != 'true')
                $this->error($msg);


            if(!isset($params['title'])){
                $this->error("请添加产品");
            }
            $product_idArr = [];
            $product_num = count($params['title']);
            for($num = 0;$num<$product_num;$num++){
                if(empty($params['title'][$num])){
                    $this->error("请填写产品名");
                }
                if(empty($params['thumbs'][$num])){
                    $this->error("请传图片信息");
                }
                if(empty($params['thumbs'][$num])){
                    $this->error("请填写价格");
                }
                if(empty($params['nums'][$num])){
                    $this->error("请填写数量");
                }
                if(empty($params['factory_id'][$num])){
                    $this->error("请选择供货商");
                }
                if(!empty($params['product_id'][$num])){
                    $product_idArr[] = $params['product_id'][$num];
                }
            }

            $ordersModel = new OrdersModel();
            $ordersProductModel = new OrdersProduct();
            $orderData = $ordersModel->where('id',$params['id'])->find();

            if($orderData['status'] >= $ordersModel::STATUS_HASSEND && $params['status'] < $orderData['status']){
                $this->error("该订单已发货，不可往前改状态");
            }

            if(empty($params['status'])){
                $this->error("状态不能不选择");
            }



            //计入记录 加库存 记账单  还要记录出库
            try {
                Db::startTrans();

                $inData['status'] = $params['status'];
                $inData['name'] = $params['name'];
                $inData['email'] = $params['email'];
                $inData['mobile'] = $params['mobile'];
                $inData['address'] = $params['address'];
                $inData['sex'] = $params['sex'];
                $inData['payaccount_id'] = $params['payaccount_id'];
                $inData['total_price'] = $params['total_price'];
                $inData['yufu_price'] = $params['yufu_price'];
                $weikuan_price = 0;
                if($params['need_weikuan'] == 1){
                    $weikuan_price = round($params['total_price']-$params['yufu_price'],2);
                }
                $inData['weikuan_price'] = $weikuan_price;
                $inData['need_weikuan'] = $params['need_weikuan'];
                $inData['remark'] = $params['remark'];
                $inData['update_time'] = date("Y-m-d H:i:s");
                $order_id = $ordersModel->where('id',$params['id'])->update($inData);


                $invoice = $orderData['order_bianhao'];

                //是否移除过商品
                $orderProductData = $ordersProductModel->where('order_bianhao',$invoice)->select();
                foreach ($orderProductData as $rowRecord){
                    if(!in_array($rowRecord['id'],$product_idArr)){
                        if($orderProductData['status'] > $ordersProductModel::STATUS_WAITDIAO){
                            $msg = $orderProductData['title']."~~状态已调货不可移除";
                            throw new \Exception($msg);
                        }
                        $ordersProductModel->where('id',$rowRecord['id'])->delete();
                    }
                }

                for($num = 0;$num<$product_num;$num++){

                    $thumbs = $params['thumbs'][$num];
                    $thumbsArr = json_decode($thumbs,true);
                    $thumb = '';
                    $all_thumb = [];
                    foreach ($thumbsArr as $key=> $oneThumb){
                        if($key == 0){
                            $thumb = $oneThumb['url'];
                        }
                        $all_thumb[] = $oneThumb['url'];
                    }

                    if(empty($params['product_id'][$num])){
                        $temp = [
                            'order_bianhao'=>$invoice,
                            'good_id'=>0,
                            'user_id'=>$admin_id,
                            'title'=>$params['title'][$num],
                            'thumb'=>$thumb,
                            'thumbs'=>implode(',',$all_thumb),
                            'guige'=>$params['guige'][$num],
                            'xinghao'=>$params['xinghao'][$num],
                            'price'=>$params['price'][$num],
                            'nums'=>$params['nums'][$num],
                            'total_price'=>round($params['price'][$num]*$params['nums'][$num],2),
                            'url'=>$params['url'][$num],
                            'remark'=>$params['remark2'][$num],
                            'attachment'=>'',
                            'factory_id'=>$params['factory_id'][$num],
                            'cost_price'=>$params['cost_price'][$num],
                            'factory_status'=>$ordersProductModel::STATUS_WAITDIAO,
                            'create_time'=>date("Y-m-d H:i:s"),
                        ];
                        $ordersProductModel->insert($temp);
                    }else{
                        $temp = [
                            'title'=>$params['title'][$num],
                            'thumb'=>$thumb,
                            'thumbs'=>implode(',',$all_thumb),
                            'guige'=>$params['guige'][$num],
                            'xinghao'=>$params['xinghao'][$num],
                            'price'=>$params['price'][$num],
                            'nums'=>$params['nums'][$num],
                            'total_price'=>round($params['price'][$num]*$params['nums'][$num],2),
                            'url'=>$params['url'][$num],
                            'remark'=>$params['remark2'][$num],
                            'attachment'=>'',
                            'factory_id'=>$params['factory_id'][$num],
                            'cost_price'=>$params['cost_price'][$num],
                            'create_time'=>date("Y-m-d H:i:s"),
                        ];
                        $ordersProductModel->where('id',$params['product_id'][$num])->update($temp);
                    }

                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                trace_log($e->getLine()."||".$e->getMessage()."||".$e->getFile(),'order_error_edit');
                $this->error($e->getMessage().$e->getLine(),'','',6);
            }

            $this->success("修改成功");
        }

        $orderData = db('orders')->find($ids);
        $productData = db('orders_product')->where('order_bianhao',$orderData['order_bianhao'])->select();
        $tableData = [];
        foreach ($productData as $item){
            $temp = [];
            $thumbsArr = explode(',',$item['thumbs']);
            $fileList = [];
            foreach ($thumbsArr as $onePic){
                $name = uniqid();
                $ttmp = [
                    'uid'=>$name,
                    'name'=>$name,
                    'url'=>$onePic,
                    'fullurl'=>request()->domain().$onePic,
                ];
                $fileList[] = $ttmp;
            }

            $temp['id'] = $item['id'];
            $temp['title'] = $item['title'];
            $temp['thumbs'] = json_encode($fileList);
            $temp['guige'] = $item['guige'];
            $temp['xinghao'] = $item['xinghao'];
            $temp['price'] = $item['price'];
            $temp['nums'] = $item['nums'];
            $temp['fileList'] = $fileList;
            $temp['total_price'] = $item['total_price'];
            $temp['url'] = $item['url'];
            $temp['remark'] = $item['remark'];
            $temp['attachment'] = $item['attachment'];
            $temp['factory_id'] = $item['factory_id'];
            $temp['cost_price'] = $item['cost_price'];
            $tableData[] = $temp;
        }

        $factoryDataArr = db('factory')->where("status",'=',1)->select();
        $accountDataArr = db('payaccount')->where("status",'=',1)->select();
        $uploadUrl = request()->domain()."/admin.php/ajax/upload";
        $this->view->assign('need_weikuan',$orderData['need_weikuan']);
        $this->view->assign('sex',$orderData['sex']);
        $this->view->assign('status',$orderData['status']);
        $this->view->assign('id',$ids);
        $this->view->assign('orderData',$orderData);

        $this->view->assign('factoryDataArr',$factoryDataArr);
        $this->view->assign('accountDataArr',$accountDataArr);
        $this->assignconfig('tableData',$tableData);
        $this->assignconfig('uploadUrl',$uploadUrl);
        return $this->view->fetch('add');
    }
    /**
     * del
     */
    public function del($ids = null)
    {
        $idsArr = explode(',',$ids);
        $ordersModel = new OrdersModel();

        foreach ($idsArr as $id){
            $order = $ordersModel->find($id);
            $ordersModel->where('id',$id)->delete();
        }
        $this->success('删除成功');
    }

    /**
     * 选择用户
     */
    public function ajaxUser(){
        $name = input('name','');
        $filed = "id,username";

        //        $word = $this->request->param()['q_word'][0];
        $page = $this->request->param('pageNumber');
        $limit = $this->request->param('pageSize');
        $page = $page ? $page : 1;
        $limit = $limit ? $limit : 20;

        if(empty($name)){
            $total = db('user')->where('id','>',0)->count();
            $data = db('user')
                ->where('id','>',0)
                ->field($filed)
                ->order('id desc')
                ->limit($limit)
                ->page($page)
                ->select();
        }else{

            if(is_numeric($name)){
                $total = db('user')->where("id",$name)->count();
                $data = db('user')
                    ->field($filed)
                    ->where("id",$name)
                    ->order('id desc')
                    ->limit($limit)
                    ->page($page)
                    ->select();
            }else{
                $total = db('user')->where("username like '%{$name}%'")->count();
                $data = db('user')
                    ->field($filed)
                    ->where("username like '%{$name}%'")
                    ->order('id desc')
                    ->limit($limit)
                    ->page($page)
                    ->select();
            }
        }

        $reData = ['list'=>[],'total'=>0];
        $list = [];
        foreach ($data as $item){
            $list[] = $item;
        }
        $reData['list'] = $list;
        $reData['total'] = $total;
        echo json_encode($reData);die();
    }
    /**
     * 选择云手机
     */
    public function ajaxPhone(){
        $name = input('name','');
        $filed = "id,name";

        //        $word = $this->request->param()['q_word'][0];
        $page = $this->request->param('pageNumber');
        $limit = $this->request->param('pageSize');
        $page = $page ? $page : 1;
        $limit = $limit ? $limit : 20;

        if(empty($name)){
            $total = db('cloudphone')->where('is_delete','=',-1)->count();
            $data = db('cloudphone')
                ->where('is_delete','=',-1)
                ->field($filed)
                ->order('id desc')
                ->limit($limit)
                ->page($page)
                ->select();
        }else{

            if(is_numeric($name)){
                $total = db('cloudphone')->where("id",$name)->count();
                $data = db('cloudphone')
                    ->field($filed)
                    ->where("id",$name)
                    ->order('id desc')
                    ->limit($limit)
                    ->page($page)
                    ->select();
            }else{
                $total = db('cloudphone')->where("name like '%{$name}%'")->count();
                $data = db('cloudphone')
                    ->field($filed)
                    ->where("name like '%{$name}%'")
                    ->order('id desc')
                    ->limit($limit)
                    ->page($page)
                    ->select();
            }
        }

        $reData = ['list'=>[],'total'=>0];
        $list = [];
        foreach ($data as $item){
            $item['name'] = $item['id'].'--'.$item['name'];
            $list[] = $item;
        }
        $reData['list'] = $list;
        $reData['total'] = $total;
        echo json_encode($reData);die();
    }
    /**
     * 选择状态
     */
    public function ajaxStatus(){
        $name = input('name','');
        $filed = "id,name";

        //        $word = $this->request->param()['q_word'][0];
        $page = $this->request->param('pageNumber');
        $limit = $this->request->param('pageSize');
        $page = $page ? $page : 1;
        $limit = $limit ? $limit : 20;

        $model = new OrdersModel();
        $statusList = $model->statusList();



        $reData = ['list'=>[],'total'=>0];
       /* $list = [];
        foreach ($statusList as $key_code => $name){
            $temp = ['id'=>$key_code,'name'=>$name];
            $list[] = $temp;
        }*/
        $reData['list'] = $statusList;
        $reData['total'] = count($statusList);
        echo json_encode($reData);die();
    }


}
